import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Executors;

public class AIOServer {
	static final ByteBuffer helloRequest = ByteBuffer.wrap("GET /hello.htm"
			.getBytes());

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup
					.withFixedThreadPool(Runtime.getRuntime()
							.availableProcessors(), Executors
							.defaultThreadFactory());
			final AsynchronousServerSocketChannel listener = AsynchronousServerSocketChannel
					.open(channelGroup).bind(new InetSocketAddress(8000));
			System.out.println("AIOServerr start...");
			listener.accept(null,
					new CompletionHandler<AsynchronousSocketChannel, Void>() {
						@Override
						public void completed(AsynchronousSocketChannel ch,
								Void attachment) {
							// accept the next connection
							listener.accept(null, this);
							// handle this connection
							handle(ch);
						}

						@Override
						public void failed(Throwable exc, Void attachment) {

						}

					});
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static void handle(final AsynchronousSocketChannel clientChannel) {
		final ByteBuffer buffer = ByteBuffer.allocate(2048);
		clientChannel.read(buffer, null,
				new CompletionHandler<Integer, ByteBuffer>() {
					@Override
					public void completed(Integer result, ByteBuffer buff) {
						if (result > 0) {
							buffer.flip();
							byte[] request = new byte[14];
							buffer.get(request, 0, 14);
							if (ByteBuffer.wrap(request)
									.compareTo(helloRequest) == 0) {
								clientChannel.write(ByteBuffer
										.wrap(("HTTP/1.1 200 OK\n"
												+ "Content-Type: text/html; charset=utf-8\n"
												+ "Content-Length: 20\n\n"
												+ "<h1>HELLO WORLD</h1>")
												.getBytes()));
								try {
									clientChannel.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							buffer.clear();
						}
						clientChannel.read(buffer, null, this);
					}

					@Override
					public void failed(Throwable exc, ByteBuffer buffer) {

					}
				});

	}

}
